var models = require('../models');
var config = require('config-lite');
var Eventproxy = require('eventproxy');
var UserProxy = require('../proxy').User;
var logger = require('../common/logger');
var tools = require('../common/tools');
var User = require('../proxy').User;

// 需要登录中间件
exports.userRequired = function (req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);
  var requestAgent = req.get('Request-Agent') || 'web';
  var oauth2 = req.get('Authorization');
  if (!oauth2) {
    res.status(401);
    return res.send_data({
      code: 401,
      message: 'Wrong Authorization'
    });
  }
  var authPcode = oauth2.split(' ')[0];
  if (authPcode === 'OAuth2') {
    var pcode = oauth2.split(' ')[1];
    if (pcode) {
      pcode = tools.decrypt(pcode, config.admin_secret).split(':');
      var plevel = pcode[0];
      pcode = pcode[1];
      logger.info('plevel: ' + plevel);
      logger.info('pcode: ' + pcode);
      models.user.findOne({
        where: {
          pcode: pcode
        },
        include: [{
          model: models.event
        }]
      }).then(function (user) {
        if (user && user.plevel === config.plevels[3] && requestAgent === 'web') {
          return res.send_data({
            code: 401,
            message: 'You don\' have permission'
          });
        }

        if (user && !user.status) {
          return res.send_data({
            code: 401,
            message: 'The user has been suspended'
          });
        }

        if (user && user.event && !user.event.status) {
          return res.send_data({
            code: 401,
            message: 'This event has been suspended'
          });
        }

        req.plevel = plevel;
        req.pcode = pcode;
        req.user = user;
        next();
      });
    }
  } else {
    res.status(401);
    return res.send_data({
      code: 401,
      message: 'Wrong type of Authorization'
    });
  }
};
